package org.example.netty.task;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * 服务端处理器
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //读消息
        System.out.println(((ByteBuf) msg).toString(CharsetUtil.UTF_8));
        //任务1
        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(10 * 1000);
                ctx.channel().writeAndFlush(Unpooled.copiedBuffer("回调2".getBytes()));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //任务2
        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(10 * 1000);
                ctx.channel().writeAndFlush(Unpooled.copiedBuffer("回调3".getBytes()));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //定时任务
        ctx.channel().eventLoop().schedule(() -> {
            try {
                Thread.sleep(10 * 1000);
                ctx.channel().writeAndFlush(Unpooled.copiedBuffer("回调4".getBytes()));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },5, TimeUnit.SECONDS);
        System.out.println("读取完毕");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        //发消息
        ctx.writeAndFlush(Unpooled.copiedBuffer("回调1".getBytes()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //异常关闭
        ctx.close();
    }
}
